package stud.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import stud.aistar.entity.*;
import stud.aistar.service.IPhoneService;
import stud.aistar.service.IUserInfoService;
import stud.aistar.service.IUserService;
import stud.aistar.util.DateUtil;
import stud.aistar.util.RandomUtils;
import stud.aistar.util.SmsLoginUtil;
import stud.aistar.util.SmsUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Jcdz on 2019/9/30.
 */

@Controller
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IPhoneService phoneService;

    @Autowired
    private IUserInfoService userInfoService;


    @GetMapping("/cloginview")
    public String  login(){
        return "showmessage/login";
    }

    @PostMapping("/clogin")
    public String clogin(String username, String password, String flag, HttpServletResponse resp, HttpServletRequest req, HttpSession session){

        User user = userService.findByUsername(username);

        if(user==null){
            user = userService.findByPhone(username);//根据姓名查找电话
        }

        if(user!=null){
            //用户存在
            if(user.getPassword().equals(password)){
                //判断是否记住密码
                if(flag!=null){
                    //将用户名和密码保存到cookie - 发送到客户端
                    String name = user.getUsername();
                    try {
                        name = URLEncoder.encode(URLEncoder.encode(username,"utf-8"),"utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    req.getSession().setAttribute("user",user);
                    req.getSession().setAttribute("username",username);
                    req.getSession().setAttribute("password",password);
                    req.getSession().setAttribute("name",name);


                    Cookie c = new Cookie("uLogin",username+":"+password);
                    //设置cookie生命周期
                    c.setMaxAge(24*60*60*30);//一个月免密登陆

                    //设置path
                    c.setPath("/");

                    //通过resp信息将cookie返回给客户端
                    resp.addCookie(c);
                    System.out.println(c);
                }else {
                    Cookie c = new Cookie("uLogin","");
                    c.setPath("/");
                    resp.addCookie(c);
                }
                System.out.println(username);
                System.out.println(password);
                System.out.println(user);



                Userinfo userinfo = userInfoService.findByUserId(user.getId());

                session.setAttribute("userinfo",userinfo);

                session.setAttribute("user",user);
                return "redirect:/index/into";//这里是首页的Controller中的注解上的路径
            }else {
                return "redirect:cloginview?error=1";
            }
        }else {
            return "redirect:cloginview?error=0";
        }

    }

    @RequestMapping("/sendMsgLogin")
    @ResponseBody
    public Result sendMsgLogin(HttpServletRequest request){

        String phoneLogin = request.getParameter("phoneLogin");
        System.out.println(phoneLogin);
        SmsLoginUtil.getPhonemsg(phoneLogin);
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        String currentTime = sf.format(calendar.getTime());
        String hash = SmsLoginUtil.getCode();
        Map<String,Object> requestMap = new HashMap<>();
        requestMap.put("hash",hash);
        requestMap.put("currentTime",currentTime);

        Phone phone = phoneService.findPhone(phoneLogin);

        if (phone == null){
            return new Result(CodeStatus.ERROR,false,"该用户不存请您注册");
        }else {
            phoneService.updatePhone(phone.getId(),Integer.valueOf(hash));
        }

        return new Result(CodeStatus.OK,true,"获取成功");
    }

    @RequestMapping("/phoneLogin")
    @ResponseBody
    public Result phoneLogin(HttpServletRequest req,HttpSession session){

        String phoneLogin = req.getParameter("phoneLogin");
        String phoneCode = req.getParameter("phoneCode");

        Phone phone = phoneService.findPhone(phoneLogin);

        if (phone == null){
            return new Result(CodeStatus.ERROR,false,"用户不存在请您注册");
        }else{
            if (phone.getCode().equals(phoneCode)){
                User user = userService.findByPhone(phoneLogin);
                Userinfo userInfo = userInfoService.findByUserId(user.getId());
                session.setAttribute("user",user);
                session.setAttribute("userInfo",userInfo);
                return new Result(CodeStatus.OK,true,"登陆成功");
            }
        }
        return new Result(CodeStatus.OK,true,"登陆成功");
    }


    @RequestMapping("/sendMsg")
    @ResponseBody
    public Map<String,Object> sendMsg(HttpServletRequest req){

        String phone = req.getParameter("phone");
        SmsUtil.getPhonemsg(phone);
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        String currentTime = sf.format(calendar.getTime());
        String hash = SmsUtil.getCode();
        Map<String,Object> requestMap = new HashMap<>();
        requestMap.put("hash",hash);
        requestMap.put("currentTime",currentTime);
        Phone ph = phoneService.findPhone(phone);
        if (ph == null) {
            Phone p = new Phone();
            p.setPhone(phone);
            p.setCode(Integer.valueOf(hash));
            phoneService.insertPhone(p);
        }else {
            requestMap.put("msg","该用户已存在，请选择登录");
        }
        return requestMap;
    }

    @RequestMapping("/register")
    @ResponseBody
    public Result register(HttpServletRequest req){

        String phone = req.getParameter("phone");
        String codeLine = req.getParameter("codeLine");
        String password = req.getParameter("password");

        Phone p = phoneService.findPhone(phone);

        if (phone!=null&&p.getCode().equals(Integer.valueOf(codeLine))){
            User user = new User();
            user.setUsername(RandomUtils.generateMixString(8));
            user.setPhone(phone);
            user.setPassword(password);
            user.setPhoneId(p.getId());
            user.setCreateTime(DateUtil.getCurrentTime());
            userService.save(user);
        }

        return new Result(CodeStatus.OK,true,+p.getCode()+"");
    }

    @RequestMapping("/forgetCode")
    @ResponseBody
    public Result regAndLogin(HttpServletRequest req){


        String newPhone = req.getParameter("newPhone");
        SmsUtil.getPhonemsg(newPhone);
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        String currentTime = sf.format(calendar.getTime());
        String hash = SmsUtil.getCode();
        Map<String,Object> requestMap = new HashMap<>();
        requestMap.put("hash",hash);
        requestMap.put("currentTime",currentTime);
        Phone newPh = phoneService.findPhone(newPhone);
        if (newPh == null){
            return new Result(CodeStatus.ERROR,false,"该用户不存请您注册");
        }else {
            phoneService.updatePhone(newPh.getId(),Integer.valueOf(hash));
        }

        return new Result(CodeStatus.OK,true,"获取成功");

    }

    @RequestMapping("udpPwd")
    @ResponseBody
    public Result udpPwd(@RequestParam String newPhone,
                         @RequestParam String newCode,
                         @RequestParam String newPwd){

        Phone phone = phoneService.findPhone(newPhone);

            if (phone.getCode().equals(newCode)) {
                User user = new User();
                user.setPassword(newPwd);
                userService.updPwd(phone.getId(),user);
            }else{
                return new Result(CodeStatus.ERROR,false,+phone.getCode()+"");
            }

        return new Result(CodeStatus.OK,true,"密码更改成功请返回登录");
    }

}
